var protocal = require('protocal');
cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    // use this for initialization
    onLoad: function () {
        var wsServerUrl = 'ws://47.93.121.107:8091/jjserver'; //线上服务器地址 
        wsServerUrl = 'ws://localhost:8091/jjserver'; 
        this.websocket = new WebSocket(wsServerUrl); //创建WebSocket对象
        
        //alert(websocket.readyState);//查看websocket当前状态
        var that = this;
        this.websocket.onopen = function (evt) {
            //已经建立连接
            cc.log("onopen");
            
            var loginObj = {};
            loginObj.id = protocal.login; 
            loginObj.token = '000';
            var loginStr = JSON.stringify(loginObj);
            that.sendMsg(loginStr);
        };
        this.websocket.onclose = function (evt) {
            //已经关闭连接
            cc.log("onclose");
        };
        this.websocket.onmessage = function (evt) {
            //收到服务器消息，使用evt.data提取
            cc.log("onmessage",evt.data);
            var jsonData = eval('(' + evt.data + ')');
            var customEvent = new cc.Event.EventCustom(jsonData.id+'', true);
            customEvent.setUserData(jsonData);
            that.node.dispatchEvent(customEvent);
        };
        this.websocket.onerror = function (evt) {
            //产生异常
            cc.log("onerror");
        };
    },
    sendMsg: function(msg){
        this.websocket.send(msg);//向服务器发送消息  
        
    },
    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});
